package com.bkhech.netty.utils;

import cn.hutool.setting.dialect.Props;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;
import java.util.Properties;
import java.util.function.Consumer;
import java.util.function.Function;

public class JedisPoolUtil {

    private static final Props properties = PropertiesUtil.getInstance();
    private static volatile JedisPool jedisPool;

    private JedisPoolUtil() {
    }

    public static <T> T executeInJedis(Function<Jedis, T> action) {
        if (jedisPool == null) {
            synchronized (JedisPoolUtil.class) {
                if (jedisPool == null) {
                    jedisPool = initJedisPool();
                }
            }
        }

        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return action.apply(jedis);
        } finally {
            jedisPool.returnResource(jedis);
        }
    }

    private static JedisPool initJedisPool() {
        int maxTotal = properties.getInt("redis.maxTotal");
        int maxIdle = properties.getInt("redis.maxIdle");
        int minIdle = properties.getInt("redis.minIdle");
        long maxWait = properties.getLong("redis.maxWait");

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大连接数
        jedisPoolConfig.setMaxTotal(maxTotal);
        // 最大空闲连接数
        jedisPoolConfig.setMaxIdle(maxIdle);
        // 最小空闲连接数
        jedisPoolConfig.setMinIdle(minIdle);
        // 最长等待时间
        jedisPoolConfig.setMaxWait(Duration.ofSeconds(maxWait));

        String serverAddr = properties.getProperty("redis.host");
        String password = properties.getProperty("redis.password");
        int port = properties.getInt("redis.port");
        int timeout = properties.getInt("redis.timeout");
        int database = properties.getInt("redis.database");
        return new JedisPool(jedisPoolConfig, serverAddr, port, timeout, password, database);
    }

}
